package com.zkyc.framework.website.util;

import com.luciad.imageio.webp.WebPReadParam;
import com.luciad.imageio.webp.WebPWriteParam;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class ImageUtils {

    public void toWebp(URL inputUrl,String outputWebpPath) throws IOException {
        //String inputPngPath = "src/main/resources/images/panda.png";
        //String inputJpgPath = "src/main/resources/images//panda.jpg";
        //URL inputJpgPath = new URL("http://10.101.116.7:9000/zj-lab/c854da81-bb2f-4f91-8e4f-d0986fff0a2e.jpg");
        //String outputWebpPath = "src/main/resources/images//hahahhaha.webp";

        // Obtain an image to encode from somewhere
        BufferedImage image = ImageIO.read(inputUrl);

        // Obtain a WebP ImageWriter instance
        ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();

        // Configure encoding parameters
        WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
        writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);

        // Configure the output on the ImageWriter
        writer.setOutput(new FileImageOutputStream(new File(outputWebpPath)));

        // Encode
        writer.write(null, new IIOImage(image, null, null), writeParam);
    }

    public void toImage(String inputWebpPath,String outputPath) throws IOException {
//        String inputWebpPath = "test_pic/test.webp";
//        String outputJpgPath = "test_pic/test_.jpg";
//        String outputJpegPath = "test_pic/test_.jpeg";
//        String outputPngPath = "test_pic/test_.png";

        // Obtain a WebP ImageReader instance
        ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

        // Configure decoding parameters
        WebPReadParam readParam = new WebPReadParam();
        readParam.setBypassFiltering(true);

        // Configure the input on the ImageReader
        reader.setInput(new FileImageInputStream(new File(inputWebpPath)));

        // Decode the image
        BufferedImage image = reader.read(0, readParam);
        ImageIO.write(image, "png", new File(outputPath));
//        ImageIO.write(image, "png", new File(outputPngPath));
//        ImageIO.write(image, "jpg", new File(outputJpgPath));
//        ImageIO.write(image, "jpeg", new File(outputJpegPath));
    }

}